package com.mmp.main.servlet.report;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mmp.common.servlet.BasicServlet;
import com.mmp.main.entity.HospitalDevicePpmDetail;
import com.mmp.main.util.Enums;
import com.mmp.main.util.WebUtil;

public class ViewPPMVisitsDetails extends BasicServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		int siteId = getSessionSiteId(request);
		int locationId = getSessionLocationId(request);
		int category = WebUtil.getParamValueAsInteger(request, "category", 0);
		int month = WebUtil.getParamValueAsInteger(request, "month", 0);
		int year = WebUtil.getParamValueAsInteger(request, "year", 0);

		Map<Integer, Object> map = new HashMap<Integer, Object>();
		int i = 0;

		String jpql = "SELECT h FROM HospitalDevicePpmDetail h WHERE h.hospitalDevice.site.id = " + siteId
				+ " AND h.hospitalDevice.status NOT IN(" + Enums.DEVICE_STATUS.SCRAPPED.getStatus() + ","
				+ Enums.DEVICE_STATUS.TRANSFERRED.getStatus() + ") AND h.visitStatus != "
				+ Enums.PPM_VISIT_STATUS.NOT_HAPPENED.getId();

		if (locationId != 0) {
			jpql += " AND h.hospitalDevice.hospital.id  = ?";
			map.put(++i, locationId);
		}

		if (category != 0) {
			jpql += " and h.hospitalDevice.category.id = ?";
			map.put(++i, category);
		}

		if (month != 0) {
			jpql += " AND MONTH(h.visitDate) = ?";
			map.put(++i, month);
		}

		if (year != 0) {
			jpql += " AND YEAR(h.visitDate) = ?";
			map.put(++i, year);
		}

		jpql += " ORDER BY h.visitDate, h.subcontractor, h.hospitalDevice.category, h.hospitalDevice.name";

		List<HospitalDevicePpmDetail> ppmList = dbQueryManager.queryJPQL(jpql, map, HospitalDevicePpmDetail.class);
		if (ppmList == null || ppmList.isEmpty()) {
			announceErorrMessage(request, response,
					"لم يتم إدخال معلومات الزيارات الوقائية للأجهزة المطلوبة في الزمن الذي تم تحديده");
			return;
		}

		request.setAttribute("ppmList", ppmList);
		viewHTMLReport(request, response, "report/ViewPPMVisitsDetails.jsp",
				Enums.REPORT_TITLE.PPM_ATTACHED_FILES.getReportTitle());

	}
}
